package com.gin.no_gay_alliance.fragment.config;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.client.NgaClient;
import com.gin.nga.enums.NgaDomain;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.BaseBindingActivity;
import com.gin.no_gay_alliance.activity.LoginActivity;
import com.gin.no_gay_alliance.adpter.NgaAccountAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.database.entity.NgaAccount;
import com.gin.no_gay_alliance.database.manager.AccountManager;
import com.gin.no_gay_alliance.databinding.FragmentConfigAccountBinding;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ClipboardUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;

import java.util.ArrayList;

/**
 * 账号管理
 */
public class ConfigAccountFragment extends BaseBindingFragment<FragmentConfigAccountBinding> implements ActivityResultCallback<ActivityResult>, View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    NgaAccountAdapter ngaAccountAdapter;
    ActivityResultLauncher<Intent> launcher;

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        ngaAccountAdapter = new NgaAccountAdapter(requireActivity(), new ArrayList<>());
        b.recyclerView.setAdapter(ngaAccountAdapter);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this);
        ViewUtils.setOnClickListener(this, b.btLoginWithCookie, b.btLoginWithPwd);

        // 域名选择
        switch (MyApplication.app.accountManager.getDomain()) {
            case com:
                b.rgDomain.check(R.id.rb_domain_ngabbs_com);
                break;
            case cn:
                b.rgDomain.check(R.id.rb_domain_nga_cn);
                break;
            case _178:
                b.rgDomain.check(R.id.rb_domain_178_com);
                break;
        }
        b.rgDomain.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_login_with_cookie) {
            addAccountDialog();
        }
        if (v.getId() == R.id.bt_login_with_pwd) {
            // 启动登录活动
            Intent intent = new Intent(requireActivity(), LoginActivity.class);
            intent.putExtra(BaseBindingActivity.INTENT_KEY_TITLE, "登录");
            launcher.launch(intent);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 加载账号列表
        ngaAccountAdapter.updateData(MyApplication.app.ngaDatabase.ngaAccountDao().listAll());
    }

    @Override
    public void onActivityResult(ActivityResult result) {
        Intent intent = result.getData();
        if (intent != null) {
            String cookie = intent.getStringExtra(LoginActivity.COOKIE_KEY);
            if (NgaClient.isCookieLegal(cookie)) {
                // cookie合法，添加到数据库中
                addAccount(cookie);
            }
        }
    }

    /**
     * 单选框切换时的回调
     *
     * @param group     单选框组
     * @param checkedId 被选中的id
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 域名选择
        if (group == b.rgDomain) {
            AccountManager accountManager = MyApplication.app.accountManager;
            if (checkedId == R.id.rb_domain_nga_cn) {
                accountManager.updateDomain(NgaDomain.cn);
            }
            if (checkedId == R.id.rb_domain_ngabbs_com) {
                accountManager.updateDomain(NgaDomain.com);
            }
            if (checkedId == R.id.rb_domain_178_com) {
                accountManager.updateDomain(NgaDomain._178);
            }
        }
    }

    private void addAccount(String cookie) {
        NgaAccount ngaAccount = MyApplication.app.accountManager.addAccount(cookie);
        // 刷新界面
        ngaAccountAdapter.insertData(ngaAccount, 0);
    }

    /**
     * 显示弹窗输入cookie
     */
    private void addAccountDialog() {
        // 创建编辑框
        EditText editText = new EditText(requireActivity());

        AlertDialog dialog = AlertDialogUtils.showConfirm(requireContext(), "添加账号", "请填写合法的Cookie", editText, (d, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                String cookie = editText.getText().toString();
                //  检查cookie是否合法
                if (NgaClient.isCookieLegal(cookie)) {
                    // cookie合法，添加到数据库中
                    addAccount(cookie);
                } else {
                    // cookie非法，弹窗提示
                    toast("Cookie不合法,请检查");
                }
            }
        });
        // 点击弹窗外部不关闭弹窗
        dialog.setCanceledOnTouchOutside(false);
        //获取焦点
        editText.requestFocus();
        // 检查剪贴板，如果发现已有cookie 自动填入
        String cookie = findCookie();
        if (cookie != null) {
            editText.setText(cookie);
            editText.setSelection(0, cookie.length());
        }
    }

    /**
     * 从剪贴板里遍历搜索cookie
     *
     * @return cookie
     */
    private String findCookie() {
        ClipboardManager clipboardManager = ClipboardUtils.getClipboardManager();
        ClipData clipData = clipboardManager.getPrimaryClip();
        if (clipData != null) {
            for (int i = 0; i < clipData.getItemCount(); i++) {
                String text = String.valueOf(clipData.getItemAt(i).getText());
                if (!ObjectUtils.isEmpty(text) && NgaClient.isCookieLegal(text)) {
                    return text;
                }
            }
        }
        return null;
    }
}